package com.bawei.auth.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bawei.auth.util.MsgUtil;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.core.utils.uuid.IdUtils;
import com.bawei.mall.user.domain.reponse.LoginResponse;
import com.bawei.mall.user.domain.request.UserInformati;
import com.bawei.mall.user.remote.RemoteUserInfo;
import com.bawei.system.domain.model.UserInformation;
import com.bawei.system.remote.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import com.bawei.common.core.constant.Constants;
import com.bawei.common.core.constant.SecurityConstants;
import com.bawei.common.core.constant.UserConstants;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.enums.UserStatus;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.system.domain.SysUser;
import com.bawei.system.domain.model.LoginUser;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static com.alibaba.nacos.api.common.Constants.ACCESS_TOKEN;

/**
 * 登录校验方法
 *
 * @author bawei
 */
@Component
public class SysLoginService
{
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MsgUtil msgUtil;

    @Autowired
    private RemoteUserInfo remoteUserInfo;

    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    /**
     * 功能：获取验证码
     * @param
     * phonenumber
     */
    public void getCode(String phonenumber) {
        // 1.校验手机号
        if(phonenumber==null){
            throw new RuntimeException("手机号不能为空！");
        }
        // 2.手机号格式
        Pattern compile = Pattern.compile("^(?:(?:\\+|00)86)?1\\d{10}$");
        boolean matches = compile.matcher(phonenumber).matches();
        if(!matches){
            throw new RuntimeException("手机号格式错误,请核对！");
        }
        // 判断手机号作为的key，在redis是否存在
        String phone = redisTemplate.opsForValue().get("phonenumber");
        if (!StringUtils.isEmpty(phone)) {
            throw new IllegalStateException("您每分钟只能请求一次代码");
        }

        // 3.校验手机号是否为当前系统用户
        R<UserInformation> tel = remoteUserService.getPhonenumber(phonenumber);
        if(tel==null){
            throw new RuntimeException("该手机号不是当前系统用户");
        }

        // 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 发送验证码
        msgUtil.sendMsg(phonenumber,code);
        // 存缓存
        redisTemplate.opsForValue().set(phonenumber,code,15, TimeUnit.MINUTES);
    }

    /**
     * 功能 登录
     * @param userInformation
     * @return
     */
    public R<LoginUser> phoneLogin(com.bawei.auth.form.UserInformation userInformation) {
        String tel = redisTemplate.opsForValue().get(userInformation.getPhonenumber());
        SysUser user = JSONObject.parseObject(tel, SysUser.class);
        if(user!=null){
            LoginUser loginUser = new LoginUser();
            loginUser.setSysUser(user);
            return R.ok(loginUser);
        }else {
            return R.fail();
        }
    }

    /**
     * 功能：新框架登录
     * @param username
     * @param password
     * @return
     */
    public R userLogin(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }

        // 查询用户信息
        R<UserInformati> userinfo = remoteUserInfo.getUser(username);
        UserInformati user = userinfo.getData();
        System.out.println("查询到的信息是"+user);
        if(!username.equals(user.getUsername())){
            throw new RuntimeException("用户错误");
        }
        if(!password.equals(user.getPassword())){
            throw new RuntimeException("密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put(IdUtils.fastUUID(),user.getUsername());
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set("aa",token);
        redisTemplate.opsForValue().set(token,JSONObject.toJSONString(user));
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token);
        loginResponse.setTokenHead("Brarer ");
        return R.ok(loginResponse);
    }

    /**
     * 功能：获取新框架登录信息
     * @return
     */
    public UserInformati getInfo() {
        String token = redisTemplate.opsForValue().get("aa");
        if (token == null || token.isEmpty()) {
            throw new ServiceException("Token为空");
        }
        String cusUserJSONString = redisTemplate.opsForValue().get(token);
        if (cusUserJSONString == null) {
            throw new ServiceException("未找到用户信息");
        }
        UserInformati userInformati = JSONObject.parseObject(cusUserJSONString, UserInformati.class);
        return userInformati;
    }

}
